<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Refresh" content="0;URL=messenger.php">
</head>

<body>
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
	require_once('php_shared/session_to_db.php');
	
	session_start();
	
	if( isset($_POST['friendname'], $_SESSION['user_id']) )
	{
		if( $_SESSION['user_id'] != '' )
		{
			$db_man = new DbUtils();
			
			if( $db_man->connect() )
			{
				$fname = $db_man->set_var( $_POST['friendname'] );
				$sql = "SELECT id FROM registered_user WHERE username=$fname";
				$result = $db_man->query($sql);
				
				if( !$result )
				{
					print "<script language = 'javascript'>alert('An error occured while communicating with database, please try again later.');</script>";
				}else{
					if( mysql_num_rows($result) > 0 )
					{
						$row = mysql_fetch_assoc($result);
						$uid = $db_man->set_var( $_SESSION['user_id'] );
						$fuid = $db_man->set_var( $row['id'] );
						$sql = "SELECT user_id FROM friend WHERE (user_id=$uid AND friend_id=$fuid) OR (user_id=$fuid AND friend_id=$uid)";
						$result = $db_man->query($sql);
						
						if( !$result )
						{
							print "<script language = 'javascript'>alert('An error occured while communicating with database, please try again later.');</script>";
						}else{
							if( mysql_num_rows($result) > 0 )
							{
								print "<script language = 'javascript'>alert('You already have a pending friend request for this user or you are already friends with the user.');</script>";
							}else{
								$sql = "INSERT INTO friend (user_id, friend_id, accepted) VALUES ($fuid, $uid, '0')";
								$result = $db_man->query($sql);
								
								if( !$result )
								{
									print "<script language = 'javascript'>alert('An error occured while communicating with database, please try again later.');</script>";
								}else{
									print "<script language = 'javascript'>alert('User will be shown in your friend list if (s)he accpets your friend request.');</script>";
								}
							}
						}
						
					}else{
						print "<script language = 'javascript'>alert('There is no user registered with the username you provided, please try again.');</script>";
					}
				}
				
				$db_man->close();
			}
		}
	}
}
?>
</body>
</html>